package nl.hu.verbrandendephoenix.controller;

import java.util.ArrayList;
import java.util.Date;

import nl.hu.verbrandendephoenix.client.AppManager;
import nl.hu.verbrandendephoenix.client.MenuManager;
import nl.hu.verbrandendephoenix.client.NotificationManager;
import nl.hu.verbrandendephoenix.shared.FieldVerifier;
import nl.hu.verbrandendephoenix.view.LoggedIn;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;
import com.google.gwt.user.client.Cookies;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;

public class Login {

	private nl.hu.verbrandendephoenix.view.Login loginForm;

	public Login(final RootPanel pnlContent) {
		String cookie = Cookies.getCookie("loginString");
		if(cookie != null && cookie.length() > 0) {
			AppManager.get().getRpcService().validLogin(cookie, new AsyncCallback<Boolean>() {
				public void onFailure(Throwable caught) {
					Window.alert("Communication Failure!");
				}
				public void onSuccess(Boolean result) {
					if(result) {
						loggedinView(pnlContent);
					} else {
						Cookies.removeCookie("loginString");
						loginView(pnlContent);
					}
				}
			});
		} else {
			loginView(pnlContent);
		}
	}

	private void loginView(Panel pnlLogin) {
		pnlLogin.clear();
		loginForm = new nl.hu.verbrandendephoenix.view.Login();
		pnlLogin.add(loginForm.constructForm());
		addHandlers();
	}

	private void loggedinView(final Panel pnlLogin) {
		pnlLogin.clear();

		AppManager.get().getRpcService().isAdmin(Cookies.getCookie("loginString"), new AsyncCallback<Boolean>() {

			public void onFailure(Throwable caught) {
				Window.alert("Communication Failure!");
			}

			public void onSuccess(Boolean result) {
				LoggedIn lI = null;
				
				if(!result)
					lI = new LoggedIn("user");
				else {
					lI = new LoggedIn("admin");
				}
				lI.getBtnLogout().addClickHandler(new ClickHandler() {
					@Override
					public void onClick(ClickEvent event) {
						Cookies.removeCookie("loginString");
						AppManager.get().getMenuManager().generateMenu();
						loginView(pnlLogin);
						History.newItem("");
					}
				});
				pnlLogin.add(lI.getPanel());
				AppManager.get().getMenuManager().generateMenu();
				AppManager.get().getHistoryListener().refresh();
			}
		});
	}

	private void processSubmit() {
		final NotificationManager nM =  NotificationManager.get();

		String s = checkFields();

		if(!s.equals("")) {
			nM.createNotification(s);
		} else {
			AppManager.get().getRpcService().loginUser(loginForm.getTxtUsername().getText(), loginForm.txtPassword.getText(), new AsyncCallback<String>() {
				public void onFailure(Throwable caught) {
					Window.alert("Communication Failure!");
				}
				public void onSuccess(String result) {
					if(result != null) {
						nM.createNotification("U bent succesvol ingelogd.");
						RootPanel pnlLogin = RootPanel.get("login");
						Date now = new Date();
						Cookies.setCookie("loginString", result, new Date(now.getYear()+2, now.getMonth(), now.getDay()));
						loggedinView(pnlLogin);
						AppManager.get().getMenuManager().generateMenu();
						//Pagina vernieuwen
						AppManager.get().getHistoryListener().refresh();
					} else {
						nM.createNotification("Incorrecte gebruikersnaam of wachtwoord.");
					}
				}
			});
		}
	}
	/**
	 * checkFields() checkt of alle velden goed zijn ingevuld.
	 * @return boolean true wanneer goed ingevuld, false wanneer fout.
	 */
	private String checkFields() {
		FieldVerifier fv = FieldVerifier.get();
		String b = ""; 

		TextBox txtUsername = loginForm.getTxtUsername();
		if(!fv.checkString(4, 30, txtUsername.getText())) {
			fv.addRequired(txtUsername);
			b += "De gebruikersnaam moet tussen de 4 en 30 tekens bevatten;";
		} else {
			fv.removeRequired(txtUsername);
		}

		TextBox txtPassword = loginForm.getTxtPassword();
		if(!fv.checkString(5, 50, txtPassword.getText())) {
			fv.addRequired(txtPassword);
			b += "Het wachtwoord moet tussen de 5 en 50 tekens bevatten;";
		} else {
			fv.removeRequired(txtPassword);
		}

		return b;
	}
	/**
	 * click & key handler, deze reageren op de ENTER toets en de submit knop.
	 */
	public void addHandlers() {
		Button btnLogin = loginForm.getBtnLogin();
		btnLogin.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				processSubmit();
			} 
		});

		ArrayList<TextBox> arrTextBoxes = loginForm.getArrTextBox();
		KeyPressHandler kphEnter = new KeyPressHandler() {
			@Override
			public void onKeyPress(KeyPressEvent event) {
				if(event.getNativeEvent().getKeyCode() == KeyCodes.KEY_ENTER) {
					processSubmit();
				}
			}
		};
		for(TextBox tb : arrTextBoxes) {
			tb.addKeyPressHandler(kphEnter);
		}

	}
}
